package com.biz.primus.ms.depot.dao.specfication;

import com.biz.primus.model.depot.enums.EmployeeRankEnum;
import com.biz.primus.model.depot.vo.EmployeePageReqVo;
import com.biz.primus.ms.depot.dao.po.Employee;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.sql.Timestamp;
import java.util.List;

/**
 * EmployeeSpecification
 *
 * @author JKLiues
 * @date 2017年10月31日
 */
@AllArgsConstructor
public class EmployeeSpecification implements Specification<Employee> {
    private EmployeePageReqVo reqVo;

    @Override
    public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        List<Predicate> predicates = Lists.newArrayList();
        if (StringUtils.isNotBlank(reqVo.getDepotCode())) {
            predicates.add(cb.equal(root.get("depotCode").as(String.class), reqVo.getDepotCode()));
        }
        if (StringUtils.isNotBlank(reqVo.getName())) {
            predicates.add(cb.like(root.get("name").as(String.class), "%s" + reqVo.getName() + "%s"));
        }
        if (reqVo.getIdentity() != null) {
            predicates.add(cb.equal(root.get("identity").as(EmployeeRankEnum.class), reqVo.getIdentity()));
        }
        Timestamp now = new Timestamp(System.currentTimeMillis());
        return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    }
}